
#include <stdint.h>
#include "Contract.h"
#include "BSP.h"
#include "Driver.h"
#include "Env.h"
#include "Event.h"

static uint8_t keyboardState;
static Timer_T backlightTimer;	//背光定时器
static int keyVal;
static uint8_t keyTime;

static void KeyBoard_Backlight_Timeout(void){
	//背光灯超时，恢复为设置的状态。
	BSP_Keyboard_Backlight_Set(envProp.backlight);
}

void KeyBoard_Backlight_Change(uint8_t state, uint16_t timeout){
	BSP_Keyboard_Backlight_Set(state);
	Timer_Reset(&backlightTimer, timeout);
}

void KeyBoard_Init(void){
	keyboardState = 0;
	Timer_Setup(&backlightTimer, 0, 0, 0, KeyBoard_Backlight_Timeout);
	//启动时，背光灯亮1秒，设置为配置的状态。
	KeyBoard_Backlight_Change(1, 100);
}


int KeyBoard_Scan(uint8_t* val){
	int ret = -1;
	int key = BSP_Keyboard_Scan();
		
	switch(keyboardState){
	case 0:{
		//无键按下,等待按键按下
		if(key>=0){
			//按键按下，若背光设置常灭则背景光亮5秒钟后熄灭，否则常亮。
			if(envProp.backlight == 0){
				KeyBoard_Backlight_Change(1, 500);
			}
			keyVal = key;
			*val = keyVal;
			keyboardState = 1;
			keyTime = 0;
			ret = KEY_E_Down;
		}
	}
	break;
	case 1:{
		//有键按下，等待按键释放
		if(key>=0){
			if(++keyTime > 50){
				//长按（5秒）				
				keyVal = key;
				*val = keyVal;
				keyboardState = 2;
				ret = KEY_E_Long;
			}
		}
		else
		{			
			keyboardState = 0;
		}
	}
	break;

	case 2:{
		if(key < 0){
			keyboardState = 0;
		}
	}
	break;
	
	default :{
		keyboardState = 0;
	}
	break;
	}
	
	return ret;
}



